package com.lanyou.cook.camel.util;

import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.lanyou.cook.camel.entity.FtpServer;


public class FtpUtil {
    
    
    private static FTPClient ftp;
    
    /**
     * 获取ftp连接
     * @param f
     * @return
     * @throws IOException 
     * @throws SocketException 
     * @throws Exception
     */
    public static boolean connectFtp(FtpServer f) throws SocketException, IOException {
        ftp=new FTPClient();
        boolean flag=false;
        int reply;
        if (f.getPort()==null) {
			ftp.connect(f.getHost(),21);
        }else{
            ftp.connect(f.getHost(),Integer.parseInt(f.getPort()));
			
        }
        ftp.login(f.getUserName(), f.getPassword());
		
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		
        reply = ftp.getReplyCode();      
        if (!FTPReply.isPositiveCompletion(reply)) {      
            ftp.disconnect();
			return flag;      
        }      
        ftp.changeWorkingDirectory(f.getFileDir());
		     
        flag = true;      
        return flag;
    }
    
    /**
     * 关闭ftp连接
     */
    public static void closeFtp(){
        if (ftp!=null && ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }   
    
    public static FTPClient getFtp(){
    	return ftp;
    }
}